var layer = layui.layer //弹层
    ,table = layui.table //表格
    form = layui.form,$ = layui.jquery,changeList=[],laydate = layui.laydate;
lay('.startTime').each(function(){
    laydate.render({
        elem: this
    });
});

let productInfo = [];
table.render({
    elem: '#purchaseorder'
    ,data:productInfo
    ,url: 'transfer/add/getSaleContractByPage'
    ,cols: [[
        {checkbox: true, sort : true,title:'选择'}
        ,{field:'customer', title:'客户名称',sort:true}
        ,{field:'customerContractNo', title:'客户合同号',sort:true}
        ,{field:'contractNo', title:'销售合同号',sort:true}
        ,{field:'companyDept', title:'签约单位',sort:true}
        ,{field:'createDate', title:'创建日期',sort:true}
        ,{field:'carryDate', title:'出运日期',sort:true}
    ]]
    ,id: 'purchaseordertableid'
    ,height: 300
    ,page: true
    ,done: function (res, curr, count) {
        table.render({
            elem: '#product'
            ,url:"transfer/add/getSaleContractProductByPage"
            ,cols: [[
                {checkbox: true, sort : true,title:'选择'}
                ,{field:'lotNo', width: 120, title: '批次号'}
                ,{field:'newContractNo', title:'销售合同号'}
                ,{field:'productCode', title:'产品编码'}
                ,{field:'specificationCode', title:'规格编码'}
                ,{field:'warehouseName',width: 120,title: '仓库名称'}
                ,{field:'specificationExplanation', title:'规格说明'}
                ,{field:'productCname', title:'中文名称'}
                ,{field:'productEname', title:'英文名称'}
                ,{field:'salesQuantity', title:'销售数量'}
                ,{field:'canTransferQuantity', title:'可调拨数量'}
                ,{field:'canApplyQuantity', title: '库存数量'}
                ,{field:'productUnit', title:'单位'}
                ,{field:'packageDesc', title:'包装说明'}
            ]]
            ,id: 'producttableid'
            ,where: {
                id:res.data.length == 0 ? "":res.data[0].contractId //默认第一条信息，数据为空则id为空
            }
            ,height: 400
            ,page: true
            ,limit: 50
            ,limits: [50, 100, 200, 300, 500]
            ,done:function () {
                $("th .layui-table-cell.laytable-cell-checkbox").html("选择");
            }
        });
    }
});

//监听复选框主表
table.on('checkbox(purchaseordertable)', function (data) {
    if(data.type == 'all'){
        //allDataOperation(data);
    }else if(data.type == 'one'){
        oneDataOperation(data);
    }

});


function oneDataOperation(data) {
    let id = data.data.contractId;
    table.reload('producttableid', {
        page: {
            curr: 1 //重新从第 1 页开始
        }
        ,where: {
            id:id
        },
        done: function (res, curr, count) {
            var child = $("#product").next().find('tbody input[type="checkbox"]');
            child.each(function(index, item){
                item.checked = data.checked;
            });
            if(data.checked){
                for(var i = 0; i < res.data.length; i++){
                    changeList.push(res.data[i]);
                }
            }else{
                if(changeList.length > 0){
                    for(var i = 0; i < res.data.length; i++){
                        deleteData(res.data[i]);
                    }
                }
            }
            form.render('checkbox');

            $("th .layui-table-cell.laytable-cell-checkbox").html("选择");
        }
    }, 'data');
}

function deleteData(data){
    let id = data.contractId;
    let stockId = data.stockId;
    for(var j = 0; j < changeList.length; j++){
        if (changeList[j].contractId == id && changeList[j].stockId == stockId) {
            changeList.splice(j, 1); // 将使后面的元素依次前移，数组长度减1
            j--; // 如果不减，将漏掉一个元素
        }
    }
}


//复选框子表
table.on('checkbox(producttable)', function (obj) {
    if ( obj.type == 'one' ) {
        if (obj.checked) {
            changeList.push(obj.data);
        } else {
            for (let index in changeList) {
                if (changeList[index].stockId == obj.data.stockId && changeList[index].contractId == obj.data.contractId) {
                    changeList.splice(index,1);
                }
            }
        }
    } else if (obj.type == 'all') {
        let tableCache = table.checkStatus("producttableid").data;
    }
    form.render('checkbox');
});

//单击行事件
table.on('row(purchaseordertable)', function (obj) {
    let id = obj.data.contractId;
    table.reload('producttableid', {
        page: {
            curr: 1 //重新从第 1 页开始
        }
        ,where: {
            id:id
        },
        parseData: function (res) {
            if (changeList) {
                for (let i in res.data) {
                    for (let j in changeList) {
                        if (changeList[j].stockId == res.data[i].stockId &&  changeList[j].contractId == res.data[i].contractId) {
                            res.data[i].LAY_CHECKED = 'true';
                        }
                    }
                }
            }
            return res;
        },
       done: function (res, curr, count) {
           $("th .layui-table-cell.laytable-cell-checkbox").html("选择");
        }
    }, 'data');

});

//提交查询条件
form.on('submit(submitform)', function(data){
    table.reload('purchaseordertableid', {
        page: {
            curr: 1 //重新从第 1 页开始
        }
        ,where: data.field
    }, 'data');
    return false;
});

$("#choose").on("click",function () {
    if(changeList.length == 0){
        layer.msg("请选择数据")
    }else{
        var oldData =  parent.table.cache["storageproductstableid"];
        var oldTransferData =  parent.table.cache["thedetailtableid"];
        if(oldTransferData.length == 0){
            oldTransferData.push(changeList[0]);
        }
        $.each(changeList, function (index, value) {
            //剔除重复数据
            let flag = true;
            if(oldData.length > 0){
                for(var i = 0; i < oldData.length; i++){
                    let sameFlag = oldData[i].stockId == changeList[index].stockId && oldData[i].contractId == changeList[index].contractId;
                    if(sameFlag){
                        flag = false;
                        break;
                    }
                }
            }
            if(flag){
                //旧仓库默认等于新仓库
                changeList[index]["newWarehouseName"] = changeList[index]["warehouseName"];
                changeList[index]["newWarehouseCode"] = changeList[index]["warehouseCode"];
                //不存在重复数据,添加数据
                oldData.push(changeList[index]);
            }
        });
        parent.table.reload('storageproductstableid', {data:oldData});
        parent.table.reload('thedetailtableid', {data:oldTransferData});
        setTimeout(function () {
            //保存成功则关闭此页面
            var index = parent.layer.getFrameIndex(window.name);
            parent.layer.close(index);
        },)
    }
})
$("#shutdown").on("click",function () {
    var index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
})